const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const Challenge = require('../models/Challenge'); // 引入 Challenge 模型
const User = require('../models/User'); // 引入 User 模型
const mongoose = require('mongoose');

// 获取所有挑战
router.get('/', async (req, res) => {
  try {
    const limit = parseInt(req.query.limit) || 10;
    const challenges = await Challenge.find()
      .sort({ createdAt: -1 })
      .limit(limit)
      .lean();
    
    res.json(challenges);
  } catch (error) {
    console.error('获取挑战列表错误:', error);
    res.status(500).json({ 
      message: '服务器错误，请稍后重试',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

// 获取单个挑战详情
router.get('/:id', async (req, res) => {
  try {
    const challenge = await Challenge.findById(req.params.id);
    if (!challenge) {
      return res.status(404).json({ message: '挑战不存在' });
    }
    res.json(challenge);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// 参与挑战
router.post('/:id/participate', auth, async (req, res) => {
    try {
        const challengeId = req.params.id;
    const userId = req.userId;

    // 验证挑战ID
    if (!mongoose.Types.ObjectId.isValid(challengeId)) {
      return res.status(400).json({ 
        message: '无效的挑战ID'
      });
    }

    // 查找挑战
    const challenge = await Challenge.findById(challengeId);
    if (!challenge) {
      return res.status(404).json({ 
        message: '挑战不存在'
      });
    }

    // 检查是否已经参与
    const alreadyParticipating = challenge.participants.some(
      p => p.userId.toString() === userId
    );

    if (alreadyParticipating) {
      return res.status(400).json({ 
        message: '您已经参与此挑战'
      });
    }

    // 添加参与者
    challenge.participants.push({
      userId,
      startDate: new Date(),
      progress: 0,
      status: 'active'
    });

    await challenge.save();

    res.json({ 
      success: true,
      message: '成功参与挑战',
      challenge
    });

  } catch (error) {
    console.error('参与挑战错误:', error);
    res.status(500).json({ 
      message: '服务器错误，请稍后重试',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
});

// 更新挑战进度
router.patch('/:id/progress', async (req, res) => {
  try {
    const { userId, progress, completedTasks } = req.body;
    const challenge = await Challenge.findById(req.params.id);

        if (!challenge) {
      return res.status(404).json({ message: '挑战不存在' });
    }

    const participant = challenge.participants.find(
      p => p.userId.toString() === userId
    );

    if (!participant) {
      return res.status(404).json({ message: '未参与此挑战' });
    }

    participant.progress = progress;
    participant.completedTasks = completedTasks;
    participant.status = progress === 100 ? 'completed' : 'active';

    await challenge.save();
    res.json(challenge);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
});

// 更新挑战进度
router.post('/:challengeId/progress', auth, async (req, res) => {
  try {
    const { taskIndex } = req.body;
    const user = await User.findById(req.user.id);
    const challenge = await Challenge.findById(req.params.challengeId);

    const activeChallenge = user.activeChallenges.find(
      ac => ac.challengeId.toString() === req.params.challengeId
    );

    if (!activeChallenge) {
      return res.status(404).json({ message: '未找到进行中的挑战' });
    }

    // 更新已完成任务
    if (!activeChallenge.completedTasks.includes(taskIndex)) {
      activeChallenge.completedTasks.push(taskIndex);
      // 更新进度
      activeChallenge.progress = 
        (activeChallenge.completedTasks.length / challenge.tasks.length) * 100;

      // 检查是否完成所有任务
      if (activeChallenge.completedTasks.length === challenge.tasks.length) {
        // 将挑战移至已完成列表
        user.completedChallenges.push({
          challengeId: challenge._id,
          completedDate: new Date(),
          earnedPoints: challenge.points
        });
        // 增加用户积分
        user.points += challenge.points;
        // 从进行中移除
        user.activeChallenges = user.activeChallenges.filter(
          ac => ac.challengeId.toString() !== req.params.challengeId
        );
      }

      await user.save();
    }

    res.json({
      progress: activeChallenge.progress,
      completedTasks: activeChallenge.completedTasks,
      points: user.points
    });
  } catch (error) {
    res.status(500).json({ message: '更新进度失败' });
  }
});

module.exports = router; 